#!-*- coding:utf-8 -*-
# vim: fileencoding=utf-8 :

# Copyright [2009] [Hiromi Hayashi]
# Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#         http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. 


import twython
import re
from datetime import *

my_name = "live_now_"


twitter = twython.setup(authtype="Basic", username="your_username", password="your_password")

def create_datetime(created_at):
    post_created_at  = datetime.strptime(created_at, "%a, %d %b %Y %H:%M:%S +0000")

    # tokyo時間にする
    post_created_at = post_created_at + timedelta(hours = 9)
    return post_created_at

def is_less_than_1hour(post_created_at):
    if post_created_at > datetime.now() + timedelta(hours = 9) - timedelta(minutes = 30):
    #if post_created_at > datetime.now() - timedelta(hours = 10):
        return True
    else:
        return False

def is_not_target_user(tweet):
    if re.search(my_name, tweet["from_user"]):
        return True

    if re.search("@" + my_name, tweet["text"]):
        return True

    if re.search("@gaetwbot|@live_now_", tweet["text"]):
        return True

    return False

def contain_ban_word(tweet):
    if re.search("^RT", tweet["text"]):
        return True

    if re.search("live_now_", tweet["text"]):
        return True
    return False

def update_status(status):

    succeeded = False

    for i in range(5):
        try:
            twitter.updateStatus(status)
            #twitter.updateStatus(status + " " + datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0000")  )
            print status
            break
        except:
            print "Exception! update Try again..." 

def post_livenow():
    for i in range(5):
        try:
            search_results = twitter.searchTwitter("ライブなう", rpp="10")
            print "search succeed." + str(len(search_results)) + "found."
            break;
        except:
            print "Exception search Try again..."

    status_livenow = []

    for tweet in search_results["results"]:
        post_created_at = create_datetime(tweet["created_at"])
        if is_less_than_1hour(post_created_at) and not contain_ban_word(tweet) and not is_not_target_user(tweet) :
            status_livenow.append(tweet)

    for tweet in status_livenow:
        cur_datetime = datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0000")
        status =  tweet["from_user"] + ": " + tweet["text"]
        status = re.sub('@', r'(at)', status)
        status = status.encode('utf-8')
        # 短縮URLの文の20文字（URL18文字、括弧2文字,スペース1文字）引く
        if len(status) > 140:
            status = status[0:118]

        postUrl = u'http://twitter.com/' + tweet["from_user"].encode('utf-8') + u'/' 

        sUrl = twitter.shortenURL(postUrl)
        update_status(status + ' [' + sUrl + ']')

def main():
    print 'Content-Type: text/plain'
    print ''
    post_livenow()

    print 'live_now_bot working!! ' + datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0000") 

if __name__ == "__main__":
  main()

